package com.sh.shanhuo.activity;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.sh.shanhuo.R;
import com.sh.shanhuo.adapter.ContentAdapter;
import com.sh.shanhuo.adapter.WebTitleAdapter;
import com.sh.shanhuo.bean.AddSiteBean;
import com.sh.shanhuo.bean.BaseBean;
import com.sh.shanhuo.bean.BoxUpdateBean;
import com.sh.shanhuo.bean.FixedPushBean;
import com.sh.shanhuo.bean.LoginBean;
import com.sh.shanhuo.bean.SiteListBean;
import com.sh.shanhuo.database.sort.SortInfoDBUtils;
import com.sh.shanhuo.database.sort.SortInfoEntity;
import com.sh.shanhuo.database.web.WebInfoDBUtils;
import com.sh.shanhuo.database.web.WebInfoEntity;
import com.sh.shanhuo.dialog.CommonEditDialog;
import com.sh.shanhuo.listener.AddSiteResultCallback;
import com.sh.shanhuo.listener.GsonObjectCallback;
import com.sh.shanhuo.listener.SimpleResultCallback;
import com.sh.shanhuo.utils.OkHttpUtil;
import com.sh.shanhuo.utils.ScreenSwitch;
import com.sh.shanhuo.utils.Tools;
import com.sh.shanhuo.view.CircleImageView;
import com.sh.shanhuo.view.CommonItemDecoration;
import com.tencent.mmkv.MMKV;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import okhttp3.Call;

public class MainActivity extends BaseActivity {
    private static final int REFRESH = 0x00;
    private LinearLayout mainLayout;
    private LinearLayout editLayout;
    private ContentAdapter contentAdapter;
    private WebTitleAdapter titlesAdapter;
    private LinearLayout webOnTopLayout, webEditorLayout, webDeleteLayout;
    private BottomSheetBehavior<RelativeLayout> behavior;
    private List<WebInfoEntity> webInfoEntities;
    private List<SortInfoEntity> sortInfoEntities;
    private EditText search;
    private TextView searchText, webOnTop;
    private CircleImageView header;
    private int currentPos, titlePos;
    private MMKV mmkv;
    public static LoginBean loginBean;
    public static String fixedPushId;
    private SmartRefreshLayout smartLayout;
    private RecyclerView titles;
    private RelativeLayout bottomSheetRl;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initData() {
        super.initData();
        mmkv = MMKV.defaultMMKV();
        if (mmkv != null) {
            boolean isLogin = mmkv.decodeBool("isLogin", false);
            if (!isLogin) {
                login();
            } else {
                loginWithCheck(mmkv.decodeString("account", ""), mmkv.decodeString("password", ""));
            }
        }
    }

    @Override
    protected void initView() {
        super.initView();
        initBottomView();
        initTitles();
        initContent();
        header = findViewById(R.id.header);
        search = findViewById(R.id.search);
        smartLayout = findViewById(R.id.smartLayout);
        ImageView toolBarEdit = findViewById(R.id.toolBarEdit);
        TextView addWebsite = findViewById(R.id.addWebsite);
        searchText = findViewById(R.id.searchText);
        TextView scanQr = findViewById(R.id.scanQr);
        TextView treasureChest = findViewById(R.id.treasureChest);

        TextView webEditor = findViewById(R.id.webEditor);
        TextView webDelete = findViewById(R.id.webDelete);
        webOnTop = findViewById(R.id.webOnTop);
        webOnTopLayout = findViewById(R.id.webOnTopLayout);
        webEditorLayout = findViewById(R.id.webEditorLayout);
        webDeleteLayout = findViewById(R.id.webDeleteLayout);

        mainLayout = findViewById(R.id.mainLayout);
        editLayout = findViewById(R.id.editLayout);
        toolBarEdit.setOnClickListener(v ->
                ScreenSwitch.startActivity(MainActivity.this, SortEditActivity.class, null));
        scanQr.setOnClickListener(v -> scan());
        addWebsite.setOnClickListener(v -> scanResult("", "", "", ""));
        header.setOnClickListener(v ->
                ScreenSwitch.startActivity(MainActivity.this, PersonalInfoActivity.class, null));
        treasureChest.setOnClickListener(v ->
                ScreenSwitch.startActivity(MainActivity.this, ToolBoxActivity.class, null));

        webEditor.setOnClickListener(v -> {
            behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
            WebInfoEntity webInfoEntity = webInfoEntities.get(currentPos);
            if (webInfoEntity.webId.equals(fixedPushId)) {
                return;
            }
            scanResult(webInfoEntity.webId, webInfoEntity.webLink, webInfoEntity.webName, webInfoEntity.description);
        });
        webDelete.setOnClickListener(v -> {
            behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
            WebInfoEntity webInfoEntity = webInfoEntities.get(currentPos);
            if (webInfoEntity.webId.equals(fixedPushId)) {
                delPush(webInfoEntity);
            } else if (webInfoEntity.permanent == 1) {
                webInfoEntity.deleteFlag = 1;
                WebInfoDBUtils.disableWebInfo(MainActivity.this, webInfoEntity);
                initFixedPush();
            } else {
                WebInfoDBUtils.delete(MainActivity.this, webInfoEntity);
                webInfoEntities = WebInfoDBUtils.getWebInfoBySortId(MainActivity.this,
                        sortInfoEntities.get(titlePos).sortName);
                initFixedPush();
            }
        });
        webOnTop.setOnClickListener(v -> {
            behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
            if (webInfoEntities.get(currentPos).onTop == 0) {
                webInfoEntities.get(currentPos).onTop = 1;
            } else {
                webInfoEntities.get(currentPos).onTop = 0;
            }
            WebInfoDBUtils.insertWebInfo(MainActivity.this, webInfoEntities.get(currentPos));
            webInfoEntities = WebInfoDBUtils.getWebInfoBySortId(MainActivity.this,
                    sortInfoEntities.get(titlePos).sortName);
            initFixedPush();
        });

        search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                searchText.setText(s.toString());
            }
        });

        search.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                searchText.setVisibility(View.VISIBLE);
            } else {
                searchText.setVisibility(View.GONE);
            }
        });


        searchText.setOnClickListener(v -> {
            searchText.setVisibility(View.GONE);
            search.clearFocus();
            if (searchText.getText().length() > 0) {
                Bundle bundle = new Bundle();
                bundle.putString("searchText", searchText.getText().toString());
                bundle.putInt("fromFlag", 2);
                ScreenSwitch.startActivity(MainActivity.this, SearchActivity.class, bundle);
            }
        });

        smartLayout.setEnableRefresh(true);
        smartLayout.setOnRefreshListener(refreshLayout -> initFixedPush());
    }

    private void delPush(WebInfoEntity webInfoEntity) {
        Map<String, String> params = new HashMap<>();
        if (mmkv.decodeBool("isLogin", false)) {
            params.put("userName", loginBean.getData().getUserName());
        } else {
            params.put("uuid", Tools.getUniquePsuedoID());
        }
        OkHttpUtil.getInstance().postForm(OkHttpUtil.IP + OkHttpUtil.DEL_PUSH, params, new GsonObjectCallback<BaseBean>() {
            @Override
            public void onUi(BaseBean baseBean) {
                if (baseBean.getCode() == 200) {
                    WebInfoDBUtils.delete(MainActivity.this, webInfoEntity);
                    webInfoEntities = WebInfoDBUtils.getWebInfoBySortId(MainActivity.this,
                            sortInfoEntities.get(titlePos).sortName);
                    initFixedPush();
                }
            }

            @Override
            public void onFailed(Call call, IOException e) {
                initFixedPush();
            }
        });
    }

    private float x;

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            x = ev.getX();
            Rect viewRect = new Rect();
            bottomSheetRl.getGlobalVisibleRect(viewRect);
            if (!viewRect.contains((int) ev.getRawX(), (int) ev.getRawY())) {
                behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
            }
            Rect viewRect2 = new Rect();
            searchText.getGlobalVisibleRect(viewRect2);
            if (!viewRect2.contains((int) ev.getRawX(), (int) ev.getRawY())) {
                search.clearFocus();
            }
        }
        if (ev.getAction() == MotionEvent.ACTION_UP) {
            if (x - ev.getX() > 150) {
                if (titlePos == sortInfoEntities.size() - 1)
                    return super.dispatchTouchEvent(ev);
                titlePos += 1;
                titles.smoothScrollToPosition(titlePos);
                titlesAdapter.setCurPos(titlePos);
                webInfoEntities = WebInfoDBUtils.getWebInfoBySortId(this,
                        sortInfoEntities.get(titlePos).sortName);
                initFixedPush();
                return true;
            }
            if (x - ev.getX() < -150) {
                if (titlePos == 0)
                    return super.dispatchTouchEvent(ev);
                titlePos -= 1;
                titles.smoothScrollToPosition(titlePos);
                titlesAdapter.setCurPos(titlePos);
                webInfoEntities = WebInfoDBUtils.getWebInfoBySortId(this,
                        sortInfoEntities.get(titlePos).sortName);
                initFixedPush();
                return true;
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    protected void onPause() {
        super.onPause();
        searchText.setVisibility(View.GONE);
        search.clearFocus();
    }

    @Override
    protected void onResume() {
        super.onResume();
        sortInfoEntities = SortInfoDBUtils.getAll(this);
        if (titlesAdapter != null) {
            titlesAdapter.setNewData(sortInfoEntities);
            if (titlePos >= sortInfoEntities.size()) {
                titlePos = 0;
            }
            webInfoEntities = WebInfoDBUtils.getWebInfoBySortId(this, sortInfoEntities.get(titlePos).sortName);
        }
        if (contentAdapter != null) {
            initFixedPush();
        }
        search.setText("");
        checkLoginState();
    }

    private void checkLoginState() {
        if (mmkv != null) {
            boolean isLogin = mmkv.decodeBool("isLogin", false);
            if (isLogin && loginBean != null) {
                Glide.with(MainActivity.this)
                        .load(loginBean.getData().getHeadUrl())
                        .placeholder(R.drawable.person_image)
                        .error(R.drawable.person_image).into(header);
            } else {
                Glide.with(MainActivity.this).load(R.drawable.person_image).into(header);
            }
        }
    }

    private void initBottomView() {
        bottomSheetRl = findViewById(R.id.bottom_sheet_rl);
        behavior = BottomSheetBehavior.from(bottomSheetRl);
        behavior.addBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, int newState) {
                Log.e("BottomSheetDemo", "newState:" + newState);
                if (newState == BottomSheetBehavior.STATE_COLLAPSED) {
                    mainLayout.setVisibility(View.VISIBLE);
                    editLayout.setVisibility(View.GONE);
                }
            }

            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {
            }
        });
    }

    private void initTitles() {
        titles = findViewById(R.id.titles);
        LinearLayoutManager manager = new LinearLayoutManager(mContext);
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        if (SortInfoDBUtils.getAll(this).size() == 0) {
            SortInfoEntity sortInfoEntity = new SortInfoEntity();
            sortInfoEntity.sortName = "默认";
            sortInfoEntity.sequence = 0;
            SortInfoDBUtils.insertSortInfo(this, sortInfoEntity);
        }
        sortInfoEntities = SortInfoDBUtils.getAll(this);
        titlesAdapter = new WebTitleAdapter(this, sortInfoEntities);
        titles.setLayoutManager(manager);
        titles.setAdapter(titlesAdapter);
        titlesAdapter.setOnItemClickListener((adapter, view, position) -> {
            titlesAdapter.setCurPos(position);
            titlePos = position;
            webInfoEntities = WebInfoDBUtils.getWebInfoBySortId(this, sortInfoEntities.get(position).sortName);
            initFixedPush();
        });
    }

    private void initContent() {
        RecyclerView website = findViewById(R.id.website);
        website.setLayoutManager(new GridLayoutManager(mContext, 2));
        website.addItemDecoration(new CommonItemDecoration(Tools.dp2px(mContext, 12),
                Tools.dp2px(mContext, 12), Tools.dp2px(mContext, 12)));
        webInfoEntities = WebInfoDBUtils.getWebInfoBySortId(this, sortInfoEntities.get(titlePos).sortName);
        contentAdapter = new ContentAdapter(this, webInfoEntities);
        website.setAdapter(contentAdapter);
        contentAdapter.setOnItemClickListener((adapter, view, position) -> {
            behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
            WebInfoEntity webInfoEntity = webInfoEntities.get(position);
            Bundle bundle = new Bundle();
            if (webInfoEntity.webId.equals(fixedPushId)) {
                String userName;
                if (loginBean == null) {
                    userName = "";
                } else {
                    userName = loginBean.getData().getUserName();
                }
                bundle.putString("userName", userName);
                ScreenSwitch.startActivity(MainActivity.this, RecommendationListActivity.class, bundle);
            } else {
                String url = webInfoEntities.get(position).webLink;
                if (TextUtils.isEmpty(url)) {
                    return;
                }
                bundle.putString("url", webInfoEntities.get(position).webLink);
                bundle.putString("id", webInfoEntities.get(position).webId);
                ScreenSwitch.startActivity(MainActivity.this, WebActivity.class, bundle);
            }
        });
        contentAdapter.setOnMoreClickListener((view, position) -> {
            webDeleteLayout.setVisibility(View.VISIBLE);
            webOnTopLayout.setVisibility(View.VISIBLE);
            webEditorLayout.setVisibility(View.VISIBLE);

            currentPos = position;
            mainLayout.setVisibility(View.GONE);
            editLayout.setVisibility(View.VISIBLE);
            behavior.setState(BottomSheetBehavior.STATE_EXPANDED);
            if (webInfoEntities.get(currentPos).onTop == 1) {
                webOnTop.setText("取消置顶");
            } else {
                webOnTop.setText("置顶");
            }

            if (webInfoEntities.get(currentPos).serverTop == 1) {
                webDeleteLayout.setVisibility(View.GONE);
                webOnTopLayout.setVisibility(View.GONE);
            }

            if (webInfoEntities.get(currentPos).lineMode == 1) {
                webOnTopLayout.setVisibility(View.GONE);
            }

            if (webInfoEntities.get(currentPos).isInServer == 1) {
                webEditorLayout.setVisibility(View.GONE);
            }
        });
    }

    private void initFixedPush() {
        onShowLoading();
        Map<String, String> params = new HashMap<>();
        if (loginBean != null) {
            params.put("userName", loginBean.getData().getUserName());
        } else {
            params.put("uuid", Tools.getUniquePsuedoID());
        }
        OkHttpUtil.getInstance().postForm(OkHttpUtil.IP + OkHttpUtil.FIXED_PUSH, params, new GsonObjectCallback<FixedPushBean>() {
            @Override
            public void onUi(FixedPushBean fixedPushBean) {
                if (fixedPushBean.getCode() == 200 && "操作成功".equals(fixedPushBean.getMsg())
                        && fixedPushBean.getData() != null) {
                    fixedPushId = fixedPushBean.getData().getId() + "";
                    WebInfoEntity webInfoEntity = new WebInfoEntity();
                    webInfoEntity.webId = fixedPushId;
                    webInfoEntity.webName = fixedPushBean.getData().getName();
                    WebInfoEntity webInfoEntity0 = WebInfoDBUtils.getWebInfoByWebId(mContext, fixedPushId);
                    if (webInfoEntity0 != null) {
                        webInfoEntity.onTop = webInfoEntity0.onTop;
                    }
                    webInfoEntity.icon = fixedPushBean.getData().getLogoUrl();
                    webInfoEntity.description = fixedPushBean.getData().getName();
                    webInfoEntity.isInServer = 1;
                    webInfoEntity.updateTime = System.currentTimeMillis();
                    WebInfoDBUtils.insertWebInfo(MainActivity.this, webInfoEntity);
                    contentAdapter.setFixedPushPos(fixedPushId, fixedPushBean.getData().getRemark());
                }
                getFirmSites();
            }

            @Override
            public void onFailed(Call call, IOException e) {
                getFirmSites();
            }
        });
    }

    private void checkOfflineData() {
        List<WebInfoEntity> all = WebInfoDBUtils.getAll(this);
        if (all.size() == 0) {
            handler.sendEmptyMessage(REFRESH);
        }
        for (WebInfoEntity webInfoEntity : all) {
            if (webInfoEntity.lineMode == 1) {
                Map<String, String> params = new HashMap<>();
                params.put("webName", webInfoEntity.webName);
                params.put("webUrl", webInfoEntity.webLink);
                params.put("introduce", webInfoEntity.description);
                String url = OkHttpUtil.IP + OkHttpUtil.ADD_SITE;
                OkHttpUtil.getInstance().postForm(url, params, new GsonObjectCallback<AddSiteBean>() {
                    @Override
                    public void onUi(AddSiteBean addSiteBean) {
                        AddSiteBean.DataBean dataBean = addSiteBean.getData();
                        if (dataBean != null) {
                            WebInfoEntity webInfoEntity1 = WebInfoDBUtils.getWebInfoByWebId(MainActivity.this, dataBean.getId());
                            if (webInfoEntity1 != null) {
                                WebInfoDBUtils.delete(MainActivity.this, webInfoEntity);
                            } else {
                                webInfoEntity.webId = dataBean.getId();
                                webInfoEntity.webName = dataBean.getWebName();
                                webInfoEntity.icon = dataBean.getLogoUrl();
                                webInfoEntity.description = (String) dataBean.getIntroduce();
                                webInfoEntity.lineMode = 0;
                                webInfoEntity.isInServer = 1;
                                webInfoEntity.updateTime = System.currentTimeMillis();
                                WebInfoDBUtils.insertWebInfo(MainActivity.this, webInfoEntity);
                            }
                        }
                        handler.sendEmptyMessage(REFRESH);
                    }

                    @Override
                    public void onFailed(Call call, IOException e) {

                    }
                });
            } else {
                handler.sendEmptyMessage(REFRESH);
            }
        }
    }

    private void login() {
        String account = "";
        String password = "";
        if (mmkv != null) {
            account = mmkv.decodeString("account");
            password = mmkv.decodeString("password");
        }
        CommonEditDialog.loginDialog(MainActivity.this, account, password, new SimpleResultCallback() {
            @Override
            public void onResult(String data1, String data2) {

            }

            @Override
            public void onButton(String action) {
                if ("forgetPassword".equals(action)) {
                    ScreenSwitch.startActivity(MainActivity.this, ForgetPasswordActivity.class,
                            null, ScreenSwitch.RESET_PASSWORD);
                } else if ("gotoRegister".equals(action)) {
                    register();
                }
            }

            @Override
            public void onBean(Object obj) {
                loginBean = (LoginBean) obj;
                if (mmkv != null) {
                    mmkv.encode("userName", loginBean.getData().getUserName());
                }
                Glide.with(MainActivity.this)
                        .load(loginBean.getData().getHeadUrl())
                        .placeholder(R.drawable.person_image)
                        .error(R.drawable.person_image).into(header);
            }
        });
    }

    private void loginWithCheck(String account, String password) {
        onShowLoading();
        Map<String, String> params = new HashMap<>();
        params.put("userName", account);
        params.put("password", password);
        OkHttpUtil.getInstance().postForm(OkHttpUtil.IP + OkHttpUtil.LOGIN, params, new GsonObjectCallback<LoginBean>() {
            @Override
            public void onUi(LoginBean bean) {
                onDismissLoading();
                if (bean.getCode() == 200 && "操作成功".equals(bean.getMsg())) {
                    loginBean = bean;
                    Toast.makeText(MainActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                    Glide.with(MainActivity.this)
                            .load(loginBean.getData().getHeadUrl())
                            .placeholder(R.drawable.person_image)
                            .error(R.drawable.person_image).into(header);
                    if (mmkv != null) {
                        mmkv.encode("isLogin", true);
                    }
                } else {
                    Toast.makeText(MainActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
                    mmkv.encode("isLogin", false);
                    login();
                }
            }

            @Override
            public void onFailed(Call call, IOException e) {
                onDismissLoading();
                Toast.makeText(MainActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
                mmkv.encode("isLogin", false);
            }
        });
    }

    private void register() {
        CommonEditDialog.registerDialog(MainActivity.this, new SimpleResultCallback() {
            @Override
            public void onResult(String data1, String data2) {
                Bundle bundle = new Bundle();
                bundle.putString("account", data1);
                bundle.putString("password", data2);
                ScreenSwitch.startActivity(MainActivity.this, AddPersonalInfoActivity.class, bundle, ScreenSwitch.REGISTER_SUCCESS);
            }

            @Override
            public void onButton(String action) {
                if ("gotoLogin".equals(action)) {
                    login();
                }
            }

            @Override
            public void onBean(Object obj) {

            }
        });
    }

    private void scan() {
        CommonEditDialog.scanDialog(this, new SimpleResultCallback() {
            @Override
            public void onResult(String data1, String data2) {
                scanResult("", data1, "", "");
            }

            @Override
            public void onButton(String action) {

            }

            @Override
            public void onBean(Object obj) {

            }
        });
    }

    private void scanResult(String id, String link, String name, String introduce) {
        CommonEditDialog.scanResultDialog(this, link, name, introduce,
                mmkv.decodeBool("isLogin", false) ? loginBean.getData().getId() + "" : "",
                mmkv.decodeBool("isLogin", false) ? loginBean.getData().getNickName() : Tools.getUniquePsuedoID(), new AddSiteResultCallback() {
                    @Override
                    public void onResult(String webUrl, String wenName, String webIntroduce) {
                        updateSite(id, webUrl, wenName, webIntroduce);
                    }

                    @Override
                    public void onResult(Object object) {
                        AddSiteBean.DataBean dataBean = (AddSiteBean.DataBean) object;
                        WebInfoEntity webInfoEntity = new WebInfoEntity();
                        webInfoEntity.icon = dataBean.getLogoUrl();
                        webInfoEntity.webId = dataBean.getId();
                        webInfoEntity.webLink = dataBean.getWebUrl();
                        webInfoEntity.webName = dataBean.getWebName();
                        webInfoEntity.isInServer = 1;
                        webInfoEntity.description = (String) dataBean.getIntroduce();
                        WebInfoEntity webInfoEntity0 = WebInfoDBUtils.getWebInfoByWebId(MainActivity.this, id);
                        if (webInfoEntity0 != null) {
                            webInfoEntity.sortName = webInfoEntity0.sortName;
                            webInfoEntity.onTop = webInfoEntity0.onTop;
                            webInfoEntity.updateTime = webInfoEntity0.updateTime;
                        }
                        WebInfoDBUtils.insertWebInfo(MainActivity.this, webInfoEntity);
                        webInfoEntities = WebInfoDBUtils.getWebInfoBySortId(MainActivity.this, sortInfoEntities.get(titlePos).sortName);
                        initFixedPush();
                    }
                });
    }

    private void updateSite(String webId, String webUrl, String webName, String webIntroduce) {
        Map<String, String> params = new HashMap<>();
        String url;
        if (!TextUtils.isEmpty(webId)) {
            params.put("id", webId);
            url = OkHttpUtil.IP +OkHttpUtil.UPDATE_SITES;
        } else {
            url = OkHttpUtil.IP +  OkHttpUtil.ADD_SITE;
        }
        params.put("webName", webName);
        params.put("webUrl", webUrl);
        params.put("introduce", webIntroduce);
        params.put("uuid", Tools.getUniquePsuedoID());
        if (mmkv.decodeBool("isLogin", false)) {
            params.put("appUserId", loginBean.getData().getId() + "");
            params.put("appUserNickName", loginBean.getData().getNickName());
        } else {
            params.put("appUserNickName", Tools.getUniquePsuedoID());
        }

        OkHttpUtil.getInstance().postForm(url, params, new GsonObjectCallback<AddSiteBean>() {
            @Override
            public void onUi(AddSiteBean addSiteBean) {
                WebInfoEntity webInfoEntity = new WebInfoEntity();
                if (addSiteBean.getCode() == 200 && "操作成功".equals(addSiteBean.getMsg()) &&
                        addSiteBean.getData() != null) {
                    webInfoEntity.icon = addSiteBean.getData().getLogoUrl();
                    webInfoEntity.webId = addSiteBean.getData().getId();
                    webInfoEntity.webLink = addSiteBean.getData().getWebUrl();
                    webInfoEntity.webName = addSiteBean.getData().getWebName();
                    webInfoEntity.description = (String) addSiteBean.getData().getIntroduce();
                } else {
                    webInfoEntity.webId = System.currentTimeMillis() + "";
                    webInfoEntity.webLink = webUrl;
                    webInfoEntity.webName = webName;
                    webInfoEntity.description = webIntroduce;
                }
                WebInfoEntity webInfoEntity0 = WebInfoDBUtils.getWebInfoByWebId(mContext, webId);
                if (webInfoEntity0 != null) {
                    webInfoEntity.sortName = webInfoEntity0.sortName;
                    webInfoEntity.onTop = webInfoEntity0.onTop;
                    webInfoEntity.updateTime = webInfoEntity0.updateTime;
                }
                WebInfoDBUtils.insertWebInfo(MainActivity.this, webInfoEntity);
                webInfoEntities = WebInfoDBUtils.getWebInfoBySortId(MainActivity.this, sortInfoEntities.get(titlePos).sortName);
                initFixedPush();
            }

            @Override
            public void onFailed(Call call, IOException e) {
                WebInfoEntity webInfoEntity = new WebInfoEntity();
                webInfoEntity.webId = System.currentTimeMillis() + "";
                webInfoEntity.webLink = webUrl;
                webInfoEntity.webName = webName;
                webInfoEntity.description = webIntroduce;
                webInfoEntity.updateTime = System.currentTimeMillis();
                webInfoEntity.lineMode = 1;
                WebInfoDBUtils.insertWebInfo(MainActivity.this, webInfoEntity);
                webInfoEntities = WebInfoDBUtils.getWebInfoBySortId(MainActivity.this, sortInfoEntities.get(titlePos).sortName);
                initFixedPush();
            }
        });
    }

    private void getFirmSites() {
        Map<String, String> params = new HashMap<>();
        params.put("pageSize", "9999");
        params.put("pageNum", "0");
        params.put("cateId", "0");
        String url = OkHttpUtil.IP + OkHttpUtil.GET_SITES;
        OkHttpUtil.getInstance().postForm(url, params, new GsonObjectCallback<SiteListBean>() {

            @Override
            public void onUi(SiteListBean siteListBean) {
                if (siteListBean.getCode() == 200) {
                    for (SiteListBean.RowsBean rowsBean : siteListBean.getRows()) {
                        WebInfoEntity webInfoEntity0 = WebInfoDBUtils.getWebInfoByWebId(mContext, rowsBean.getId());
                        WebInfoEntity webInfoEntity = new WebInfoEntity();
                        webInfoEntity.webId = rowsBean.getId();
                        if (webInfoEntity0 != null) {
                            if (webInfoEntity0.deleteFlag == 1) {
                                break;
                            }
                            webInfoEntity.sortName = webInfoEntity0.sortName;
                            webInfoEntity.onTop = webInfoEntity0.onTop;
                            webInfoEntity.updateTime = webInfoEntity0.updateTime;
                        }
                        webInfoEntity.permanent = 1;
                        webInfoEntity.webLink = rowsBean.getWebUrl();
                        webInfoEntity.icon = rowsBean.getLogoUrl();
                        webInfoEntity.webName = rowsBean.getWebName();
                        webInfoEntity.description = rowsBean.getIntroduce();
                        webInfoEntity.serverTop = rowsBean.getTop();
                        webInfoEntity.isInServer = 1;
                        WebInfoDBUtils.insertWebInfo(MainActivity.this, webInfoEntity);
                    }
                    getWebSite();
                }
            }

            @Override
            public void onFailed(Call call, IOException e) {
                getWebSite();
            }
        });
    }

    private void getWebSite() {
        StringBuilder ids = new StringBuilder();
        for (WebInfoEntity webInfoEntity : webInfoEntities) {
            if (webInfoEntity.fromBox == 1) {
                ids.append(webInfoEntity.webId).append(",");
            }
        }
        Map<String, String> params = new HashMap<>();
        params.put("ids", TextUtils.isEmpty(ids) ? "" : ids.substring(0, ids.lastIndexOf(",")));
        String url = OkHttpUtil.IP + OkHttpUtil.WEB_SITES;
        OkHttpUtil.getInstance().postForm(url, params, new GsonObjectCallback<BoxUpdateBean>() {

            @Override
            public void onUi(BoxUpdateBean boxUpdateBean) {
                if (boxUpdateBean.getCode() == 200 && boxUpdateBean.getData() != null) {
                    for (BoxUpdateBean.DataBean dataBean : boxUpdateBean.getData()) {
                        WebInfoEntity webInfoEntity = new WebInfoEntity();
                        webInfoEntity.webId = dataBean.getId();
                        WebInfoEntity webInfoEntity0 = WebInfoDBUtils.getWebInfoByWebId(mContext, dataBean.getId());
                        if (webInfoEntity0 != null) {
                            webInfoEntity.sortName = webInfoEntity0.sortName;
                            webInfoEntity.fromBox = webInfoEntity0.fromBox;
                            webInfoEntity.onTop = webInfoEntity0.onTop;
                            webInfoEntity.updateTime = webInfoEntity0.updateTime;
                        }
                        webInfoEntity.webLink = dataBean.getWebUrl();
                        webInfoEntity.icon = dataBean.getLogoUrl();
                        webInfoEntity.webName = dataBean.getWebName();
                        webInfoEntity.description = dataBean.getIntroduce();
                        webInfoEntity.serverTop = dataBean.getTop();
                        webInfoEntity.isInServer = 1;
                        WebInfoDBUtils.insertWebInfo(MainActivity.this, webInfoEntity);
                    }
                }
                checkOfflineData();
            }

            @Override
            public void onFailed(Call call, IOException e) {
                handler.sendEmptyMessage(REFRESH);
            }
        });
    }


    private synchronized void refreshAdapter() {
        webInfoEntities = WebInfoDBUtils.getWebInfoBySortId(this, sortInfoEntities.get(titlePos).sortName);
        Collections.sort(webInfoEntities, (o1, o2) -> (int) (o2.updateTime - o1.updateTime));
        Collections.sort(webInfoEntities, (o1, o2) -> o2.onTop - o1.onTop);
        Collections.sort(webInfoEntities, (o1, o2) -> o2.serverTop - o1.serverTop);
        contentAdapter.setNewData(webInfoEntities);
    }

    private long pressedTime;

    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() - pressedTime < 2000) {
            super.onBackPressed();
            finish();
        } else {
            Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show();
            pressedTime = System.currentTimeMillis();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ScreenSwitch.REGISTER_SUCCESS ||
                requestCode == ScreenSwitch.RESET_PASSWORD) {
            login();
        }
    }

    private final Handler handler = new Handler(msg -> {
        if (msg.what == REFRESH) {
            smartLayout.finishRefresh();
            onDismissLoading();
            refreshAdapter();
        }
        return false;
    });
}